package com.jiuqi.abc.model.web;

import com.jiuqi.abc.ABCException;
import com.jiuqi.abc.intf.provider.table.*;
import com.jiuqi.abc.model.bean.ResourceMemberValue;
import com.jiuqi.abc.model.service.ABCResourceMemberService;
import com.jiuqi.abc.model.vo.DimensionMemberVo;
import com.jiuqi.abc.model.vo.TreeNodeVo;
import com.jiuqi.np.core.restapi.annotation.PermissionsResourceGroup;
import com.jiuqi.nvwa.sf.anno.Licence;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 龚泽楷
 * @date 2023年04月25日 16:03
 */
@Api(tags = {"abc模型成本池维度成员管理"})
@RestController
@CrossOrigin
@RequestMapping("abc/model/resourceMember")
@PermissionsResourceGroup("abc模型成本维度管理")
@Licence(module="com.jiuqi.abc.modelmanager", point="com.jiuqi.abc.function")
public class ABCResourceMemberController {

    public static final String STATUS = "status";
    @Autowired
    private ABCResourceMemberService abcResourceMemberService;


    @ApiOperation("获取维成员列表（成本池）")
    @GetMapping("list/{modelId}")
    public Map<String, Object> getDimensionMemberList(@PathVariable("modelId") String modelId) {
        List<DimensionMemberVo> memberResourceList = abcResourceMemberService.getResourceMemberTreeList(modelId);

        //添加ncell 总展示条目数
        int totalCount = 0;
        if (memberResourceList != null){
            for (DimensionMemberVo dimensionMemberVo : memberResourceList) {
                totalCount += dimensionMemberVo.getSubDimItemCount() + 1;
            }
        }


        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("showList", memberResourceList == null?new ArrayList<>() : memberResourceList);
        result.put("totalCount", totalCount);

        return result;
    }

    @ApiOperation("导入")
    @PostMapping("import/{modelId}")
    public Map<String, Object> importData(@PathVariable("modelId") String modelId, @RequestParam("file") MultipartFile file) {
        HashMap<String, Object> result = new HashMap<>();

        boolean isSuccess = true;
        try {
            abcResourceMemberService.processImportData(modelId, file);
        } catch (ABCException e) {
            isSuccess = false;
            result.put("cause", e.getMessage());
        } finally {
            if (isSuccess) {
                result.put(STATUS, "成功");
            }else {
                result.put(STATUS, "失败");
            }
        }

        return result;
    }

    @ApiOperation("导出")
    @PostMapping("export/{modelId}")
    public void exportData(@PathVariable("modelId") String modelId, HttpServletResponse response) {
        abcResourceMemberService.processExportData(modelId, response);
    }

    @ApiOperation("保存")
    @PostMapping("save/{modelId}")
    public Map<String, Object> save(@RequestBody List<ResourceMemberValue> resourceMemberValues, @PathVariable("modelId") String modelId) {

        abcResourceMemberService.saveResourceMember(resourceMemberValues, modelId);

        HashMap<String, Object> result = new HashMap<>();
        result.put(STATUS, "成功");
        return result;
    }

    @ApiOperation("生成取数公式_获取取数表")
    @GetMapping("generateFormula/dataTableList/{modelId}/{folderId}")
    public Map<String, Object> getDataTableList(@PathVariable("modelId") String modelId, @PathVariable("folderId") String folderId) {
        //获取 数据方案，创建根节点
        List<TreeNodeVo> rootNodeArr = new ArrayList<>();
        if ("null".equals(folderId))
            rootNodeArr.add(abcResourceMemberService.getRootNode(modelId));

        List<TreeNodeVo> treeNodeList = new ArrayList<>();
        //获取数据表
        List<TableObj> tableObjs = abcResourceMemberService.getDataTableList(modelId, folderId);

        //转换树形格式
        for (TableObj tableObj : tableObjs) {
            if (tableObj instanceof TableBean) {
                TableBean tableBean = (TableBean) tableObj;
                if (tableBean.getType() == TableType.SINGLE_DIM || tableBean.getType() == TableType.MULTI_DIM) {
                    TreeNodeVo treeNodeVo = new TreeNodeVo(tableBean);
                    treeNodeList.add(treeNodeVo);
                }
            } else {
                TreeNodeVo treeNodeVo = new TreeNodeVo((TableFolder) tableObj);
                treeNodeList.add(treeNodeVo);
            }
        }

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("rootNodeArr", rootNodeArr);
        result.put("tableList", treeNodeList);
        result.put(STATUS, "成功");

        return result;
    }

    @ApiOperation("生成取数公式_获取表字段")
    @GetMapping("generateFormula/tableField/{tableName}")
    public Map<String, Object> getTableFieldList(@PathVariable("tableName") String tableName) {
        //获取获取表字段
        List<Field> tableFieldList = abcResourceMemberService.getTableFieldList(tableName);

        //指标字段集合
        List<Field> zbList = new ArrayList<>();

        //维度字段集合
        List<Field> wdList = new ArrayList<>();

        //分流
        for (Field field : tableFieldList) {
            if (field.isDim())
                wdList.add(field);

            if (!field.isDim() && "数值".equals(field.getDataTypeTitle()))
                zbList.add(field);
        }

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("zbList", zbList);
        result.put("wdList", wdList);
        result.put(STATUS, "成功");

        return result;
    }


}
